import { Component, OnInit, Input, EventEmitter, Output, AfterViewInit, OnChanges } from '@angular/core';

@Component({
    selector: 'mpj-checkbox-group',
    styleUrls: ['./widgets.scss'],
    template: `
        <div class="checkbox-group-container" *ngIf="sourceOptions" fxLayout="row" fxLayoutWrap="wrap">
            <md-checkbox class="margin-t-m" fxFlex="25%" [(ngModel)]="checkedAll" (change)="changeAll($event)" item>全部</md-checkbox>
            <md-checkbox class="margin-t-m" fxFlex="25%" *ngFor="let VOOption of VOOptions;trackBy:trackById" (change)="changeOption($event,VOOption)" [(ngModel)]="VOOption.checked" item>{{VOOption.label}}</md-checkbox>
        </div>
    `
})


export class MPJCheckboxGroup implements OnInit, AfterViewInit, OnChanges {
    @Input() checkedValues: string[] = []
    @Input() isIndeterminate: boolean
    @Input() sourceOptions: Array<{ id: string, label: string }>

    @Output() onChange = new EventEmitter<Array<string>>();
    @Output() checkedValuesChange = new EventEmitter<Array<string>>();

    VOOptions: Array<{ id: string, checked: boolean, label: string }>

    constructor() { }
    get checkedAll() {
        if (this.VOOptions.every(x => x.checked)) return true;
        else return false;
    }

    changeAll(event: { checked: boolean }) {
        if (!event.checked) {
            this.VOOptions.forEach(x => x.checked = false)
        } else {
            this.VOOptions.forEach(x => x.checked = true)
        }
        this.change();
    }

    changeOption(event: { checked: boolean }, option) {
        this.change();
    }

    ngOnChanges(change) {
        if (change.checkedValues) {
            this.refreshVOOptions();
        }
    }

    change() {
        const checkedValues = this.VOOptions.filter(x => x.checked).map(x => x.id)
        this.checkedValuesChange.emit(checkedValues);
        this.onChange.emit(checkedValues);
    }

    ngOnInit() {
        this.checkedValues = this.checkedValues || [];
        this.refreshVOOptions();
    }

    refreshVOOptions() {
        const sourceVOOptions = this.sourceOptions.map(option => {
            return {
                id: option.id,
                label: option.label,
                checked: this.checkedValues && this.checkedValues.indexOf(option.id) > -1
            }
        })
        this.VOOptions = sourceVOOptions;
    }

    ngAfterViewInit() {
        // this.change();
    }

    trackById(index, item) {
        return item.id;
    }
}